<script setup>
import { Plus, Upload } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { useUserStore } from '@/stores'

const uploadRef = ref(null)
const userStore = useUserStore()
// 基于user的数据初始化imgUrl
const imgUrl = ref(userStore.user.user_pic)

// 点击选择图片，触发upload的选择图片
const onSelectImg = () => {
  uploadRef.value.click()
  console.log(uploadRef.value)
}
// 点击上传图片，触发upload的上传图片
const onUploadImg = () => {}

const onSelectFile = (file) => {
  // 1.创建formData对象
  const formData = new FormData()
  // 2.将file对象添加到formData对象中
  formData.append('avatar', file.raw)
  // 3.发送请求
  // 3.1.发送请求之前，将用户信息中的头像地址保存下来
  // const oldAvatar = userStore.user.user_pic
}
</script>

<template>
  <page-container title="更换头像">
    <el-upload
      :auto-upload="false"
      class="avatar-uploader"
      :show-file-list="false"
      :on-change="onSelectFile"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <el-button @click="onSelectImg" type="primary" size="large" :icon="Plus"
      >选择图片</el-button
    >
    <el-button type="success" size="large" :icon="Upload" @click="onUploadImg"
      >上传图片</el-button
    >
  </page-container>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}

.el-button {
  margin-top: 20px;
}
</style>
